package com.czk.zookeeper.curator.delete;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/7 21:32
 */
public class CuratorDeleteTest {
    String IP = "192.168.25.133:2181,192.168.25.133:2182,192.168.25.133:2183";
    CuratorFramework client;

    @Before
    public void before() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder()
                .connectString(IP)
                .sessionTimeoutMs(50000)
                .retryPolicy(retryPolicy)
                .namespace("delete")
                .build();
        client.start();
    }

    @After
    public void after() {
        client.close();
    }

    @Test
    public void test1() throws Exception {
        client.delete()
                .withVersion(-1)
                .forPath("/node1");
        System.out.println("结束");
    }

    /**
     * 删除拥有子节点的节点
     *
     * @throws Exception
     */
    @Test
    public void test2() throws Exception {
        client.delete()
                // 删除其子节点
                .deletingChildrenIfNeeded()
                .withVersion(-1)
                .forPath("/node2");
        System.out.println("结束");
    }

    /**
     * 异步方式删除子节点
     *
     * @throws Exception
     */
    @Test
    public void test3() throws Exception {
        client.delete()
                .deletingChildrenIfNeeded()
                .withVersion(-1)
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                        System.out.println(curatorEvent.getPath());
                        System.out.println(curatorEvent.getType());
                    }
                })
                .forPath("/node1");
    }
}
